﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;

namespace Beeline {
	class BeelineControl {
		public HttpListener Listener;
		public bool Listen;
		public void StartListening(){ StartListening(8331); }
		public void StartListening(int PortNumber){
			if(!HttpListener.IsSupported){
				throw new Exception("OS not supported.");
			}
			else {
				Listener = new HttpListener();
				Listener.Prefixes.Add(String.Format("http://localhost:{0}/",PortNumber));
				Listen = true;
				Listener.Start();
				
				Thread listenerThread = new Thread(new ThreadStart(Handler));
				listenerThread.Start();
			}
		}

		private void Handler(){
			while(Listen){
				IAsyncResult result = Listener.BeginGetContext(new AsyncCallback(ListenerCallback), Listener);
				result.AsyncWaitHandle.WaitOne();
			}
			Listener.Close();
		}

		private void ListenerCallback(IAsyncResult Result){
			HttpListenerContext context = Listener.EndGetContext(Result);
			// Code here.
			BeelineEngine engine = new BeelineEngine(context.Request.RawUrl);
			string resultUrl = engine.Parse(context.Request.RawUrl);
			if(!String.IsNullOrEmpty(resultUrl)){
				HttpListenerResponse response = context.Response;
				response.Redirect(resultUrl);
				response.Close();
			}
			
			Handler();
		}

		public void StopListening(){
			Listen = false;
			Listener.Stop();
		}

	}
}
